#ifndef O_LARGEFILE
#define O_LARGEFILE 0100000
#endif
#define _GNU_SOURCE
#define _LARGEFILE_SOURCE  
#define _LARGEFILE64_SOURCE  
#define _FILE_OFFSET_BITS 64
#include <jni.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <ctype.h>
#include <stdint.h>
#include <limits.h>
#include <sys/file.h>
#include "tr_edu_ozyegin_ccrg_raid_rawdisk_DiskReader.h"

JNIEXPORT jbyteArray JNICALL Java_tr_edu_ozyegin_ccrg_raid_rawdisk_DiskReader_loadFile
  (JNIEnv * env, jobject jobj, jstring name, jlong blockID, jlong blockSize){
    int fd;
  unsigned char *buffer;
  int i, j,readed=0;
	buffer = (char *)malloc((int)((uint64_t)blockSize));
uint64_t BlockSize = (uint64_t)blockSize ;
uint64_t BlockID  = (uint64_t)blockID;
jboolean iscopy;
      const jchar *mfile = (*env)->GetStringUTFChars(env, name, &iscopy);
		//printf("\n%s\n",mfile);
  fd = open64(mfile, O_RDONLY | O_LARGEFILE);
  if (fd < 0){
    printf("Opening failed\n"); 
    return 0;
  } //end-if
  readed = 0;
  if(BlockID !=0){
  	int i;
  	uint64_t seeked = 0;
  	//uint64_t toSeek = BlockSize * BlockID;
  	seeked = lseek64(fd,BlockID,SEEK_SET);
  	if(seeked < 0){ return 0;}
  }
  
  
  while(1){
	int nreaded;
  	(nreaded = read(fd, buffer+readed, ((int)(blockSize) - readed)));
	if(nreaded <=0) return 0;
	readed += nreaded;
  	//printf("%d , %lu \n",(int)readed,(long)blockSize);
  	if(readed == (int)blockSize) break;
  }
//printf("%d bytes\n",readed);
jbyteArray jb;
  jb=(*env)->NewByteArray(env, blockSize);
  (*env)->SetByteArrayRegion(env, jb, 0,blockSize, (jbyte *)buffer);
  //jbyte *bytes = (*env)->GetByteArrayElements(env,jb,NULL);
  (*env)->ReleaseStringChars(env, name, mfile);
  (*env)-> ReleaseByteArrayElements(env, jb, (jbyte *)buffer, 0);
  //free(bytes);
  //free(buffer);
  close(fd);
    return (jb);
}
